var express = require('express');
var router = express.Router();
var md5 = require('md5');
var fs = require('fs');

var db_config = require('../conn');

router.get('/login', function(req, res, next) {
	res.render("login",{title: '登录'});
})
router.post('/login',function(req,res,next){
	req.body.password = md5(req.body.password);
	var sql = 'select * from users where name="'+req.body.name+'" and password="'+req.body.password+'"';
	conn.query(sql,function(err,rows,fields){
		if (rows.length == 0) {
			res.send("账号或密码错误，请重新输入");
		}else{
			req.session.username = req.body.name;
			if (req.session.username== "admin") {
				req.session.is_login = true;
				res.send('admin')
			}else{
				res.send('ok')
			}
		}

	})
})

router.get('/signup', function(req, res, next) {
	res.render("signup",{
		title: '注册',
		errPassword: req.flash('errPassword'),
		errName: req.flash('errName'),
		same: req.flash('same')
	});
})
router.post('/signup', function(req, res, next) {
	if (req.body.name=="" || req.body.password=="") {
		if (req.body.name=="") {
			req.flash('errName','请输入用户名')
		}
		if (req.body.password=="") {
			req.flash('errPassword','请输入密码')
		}
		res.redirect('/users/signup');
	}else{
		var sql = 'select * from users where name="'+req.body.name+'"';
		conn.query(sql,function(err,rows,fields){
			if (rows.length==0) {
				req.body.password = md5(req.body.password);
				var sql = 'insert into users values (null,"'+req.body.name+'","'+req.body.password+'")';
				conn.query(sql,function(err,rows,fields){
					res.redirect('/users/login');
				})			
			}else{
				req.flash('same','用户名已被注册');
				res.redirect('/users/signup');
			}
		})	
	}

})

router.get('/signout', function(req, res, next) {
	req.session.destroy();
    res.redirect('/');
})

module.exports = router;
